package LinkedList;

import Node.ListNode;

/**
 * 删除单链表中倒数第k个节点
 */
public class RemoveNthFromEnd {

    public ListNode removeNthFromEnd(ListNode head, int k) {
        if (head == null)
            return null;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        // 要想删除倒数k节点，需先找到倒数k+1个节点
        ListNode node = findFromEnd(head, k + 1);
        node.next= node.next.next;
        return dummy.next;

    }
    private ListNode findFromEnd(ListNode head, int k) {
        if (head == null)
            return null;
        ListNode p1 = head;
        for (int i = 0; i < k; i++) {
            p1 = p1.next;
        }
        ListNode p2 = head;
        while (p1 != null) {
            p1 = p1.next;
            p2 = p2.next;
        }
        return p2;
    }
}
